<template>
  <PageContainer title="客服状态管理">
    <!-- 头部操作区：状态选择 + 切换按钮 -->
    <template #extra>
      <div class="status-switch-container">
        <!-- 状态选择下拉框：修复size属性为default -->
        <el-select
          v-model="selectedStatus"
          placeholder="选择在线状态"
          size="default"
          class="status-select"
          :disabled="isLoading"
        >
          <el-option label="在线" value="online"></el-option>
          <el-option label="离线" value="offline"></el-option>
          <el-option label="忙碌" value="busy"></el-option>
        </el-select>

        <!-- 状态切换按钮：加载中禁用点击 -->
        <el-button
          type="primary"
          @click="handleSwitchStatus"
          :loading="isLoading"
          icon="el-icon-refresh"
        >
          确认切换
        </el-button>
      </div>
    </template>

    <!-- 主体内容：当前用户信息展示 -->
    <div class="status-info-card">
      <el-card shadow="hover" :border="false">
        <div class="info-item">
          <span class="label">当前账号：</span>
          <span class="value">{{ userStore.user.username || '未加载' }}</span>
        </div>
        <div class="info-item">
          <span class="label">当前角色：</span>
          <span class="value">{{ formatRole(userStore.user.role) }}</span>
        </div>
        <div class="info-item">
          <span class="label">当前状态：</span>
          <span class="value">
            <el-tag :type="getStatusTagType(userStore.user.status)">
              {{ formatStatus(userStore.user.status) }}
            </el-tag>
          </span>
        </div>
      </el-card>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElTag } from 'element-plus';
import PageContainer from '@/components/PageContainer.vue';
import { useUserStore } from '@/stores/admin';
import { changeStatus } from '@/api/service';

// 状态管理
const userStore = useUserStore();
const selectedStatus = ref('offline');
const isLoading = ref(false);

// 组件挂载：初始化用户信息和状态
onMounted(async () => {
  try {
    isLoading.value = true;
    await userStore.initUser();
    
    const currentStatus = userStore.user.status || 'offline';
    selectedStatus.value = currentStatus;
    debugLog('初始化完成', { username: userStore.user.username, currentStatus });
  } catch (error) {
    ElMessage.error('用户信息加载失败：' + (error.message || '网络异常'));
    debugLog('初始化失败', error);
  } finally {
    isLoading.value = false;
  }
});

// 辅助函数：格式化角色显示
const formatRole = (role) => {
  const roleMap = {
    customer_service: '普通客服',
    reviewer: '审核员',
    editor: '责任编辑',
    super_admin: '高级管理员'
  };
  return roleMap[role] || '未知角色';
};

// 辅助函数：格式化状态显示 + 标签样式
const formatStatus = (status) => {
  const statusMap = { online: '在线', offline: '离线', busy: '忙碌' };
  return statusMap[status] || '未设置';
};
const getStatusTagType = (status) => {
  const typeMap = { online: 'success', offline: 'info', busy: 'warning' };
  return typeMap[status] || 'default';
};

// 核心逻辑：状态切换（修复错误提示+状态更新）
const handleSwitchStatus = async () => {
  if (isLoading.value) return;
  
  const targetStatus = selectedStatus.value;
  
  // 校验：状态未重复
  if (targetStatus === userStore.user.status) {
    ElMessage.info('当前已是「' + formatStatus(targetStatus) + '」状态，无需切换');
    return;
  }

  try {
    isLoading.value = true;
    debugLog('发起状态切换请求', { targetStatus });
    
    // 调用状态切换接口
    const res = await changeStatus({ status: targetStatus });
    
    // 接口请求成功（无异常），处理响应
    if (res.data.success) {
      ElMessage.success('状态切换成功！当前状态：' + formatStatus(targetStatus));
      // 更新Pinia仓库状态（同步UI）
      userStore.setUser({ ...userStore.user, status: targetStatus });
    } else {
      ElMessage.error('切换失败：' + (res.message || '接口响应异常'));
    }
  } catch (error) {
    // 捕获请求异常，但额外检查是否实际切换成功
    const responseData = error.response?.data; // 取后端返回的响应体
    if (responseData?.success) {
      // 实际已成功，强制更新状态+显示成功提示
      ElMessage.success('状态切换成功！当前状态：' + formatStatus(targetStatus));
      userStore.setUser({ ...userStore.user, status: targetStatus });
    } else {
      // 真的失败，显示错误提示
      ElMessage.error('请求异常：' + (error.message || '网络错误'));
    }
    debugLog('状态切换请求异常', error);
  } finally {
    isLoading.value = false;
  }
};

// 调试工具：仅开发环境打印日志
const debugLog = (message, data) => {
  if (import.meta.env.DEV) {
    console.groupCollapsed(`🔍 [状态管理] ${message}（${new Date().toLocaleTimeString()}）`);
    Object.entries(data).forEach(([key, value]) => {
      console.log(`${key}:`, value);
    });
    console.groupEnd();
  }
};

// 监听用户状态变化（同步下拉框选中值）
watch(
  () => userStore.user.status,
  (newStatus) => {
    if (newStatus) selectedStatus.value = newStatus;
  }
);
</script>

<style lang="scss" scoped>
.status-switch-container {
  display: flex;
  gap: 12px;
  align-items: center;
  .status-select {
    width: 140px;
  }
}
.status-info-card {
  margin-top: 20px;
  .el-card {
    padding: 24px;
  }
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    &:last-child {
      margin-bottom: 0;
    }
    .label {
      width: 80px;
      font-size: 14px;
      color: #666;
    }
    .value {
      font-size: 14px;
      color: #333;
    }
  }
}
</style>